3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
13 * Update this version number when the ParserOutput format
14 * changes in an incompatible way, so the parser cache
15 * can automatically discard old data.
17 define( 'MW_PARSER_VERSION', '1.5.0' );
20 * Variable substitution O(N^2) attack
22 * Without countermeasures, it would be possible to attack the parser by saving
23 * a page filled with a large number of inclusions of large pages. The size of
24 * the generated page would be proportional to the square of the input size.
25 * Hence, we limit the number of inclusions of any given page, thus bringing any
26 * attack back to O(N).
29 define( 'MAX_INCLUDE_REPEAT', 100 );
30 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
32 define( 'RLH_FOR_UPDATE', 1 );
34 # Allowed values for $mOutputType
35 define( 'OT_HTML', 1 );
36 define( 'OT_WIKI', 2 );
37 define( 'OT_MSG' , 3 );
39 # string parameter for extractTags which will cause it
40 # to strip HTML comments in addition to regular
41 # <XML>-style tags. This should not be anything we
42 # may want to use in wikisyntax
43 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
45 # prefix for escaping, used in two functions at least
46 define( 'UNIQ_PREFIX', 'NaodW29');
48 # Constants needed for external link processing
49 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
50 define( 'HTTP_PROTOCOLS', 'http|https' );
51 # Everything except bracket, space, or control characters
52 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
54 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
55 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
56 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
57 define( 'EXT_LINK_BRACKETED', '/\[(\b('.URL_PROTOCOLS
.'):'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
58 define( 'EXT_IMAGE_REGEX',
59 '/^('.HTTP_PROTOCOLS
.':)'. # Protocol
60 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
61 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
67 * Processes wiki markup
70 * There are three main entry points into the Parser class:
72 * produces HTML output
74 * produces altered wiki markup.
76 * performs brace substitution on MediaWiki messages
79 * objects: $wgLang, $wgLinkCache
81 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
84 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
85 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
88 * * only within ParserOptions
101 # Cleared with clearState():
102 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
103 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
104 var $mInterwikiLinkHolders, $mLinkHolders;
107 var $mOptions, $mTitle, $mOutputType,
108 $mTemplates, // cache of already loaded templates, avoids
109 // multiple SQL queries for the same string
110 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
111 // in this path. Used for loop detection.
122 $this->mTemplates
= array();
123 $this->mTemplatePath
= array();
124 $this->mTagHooks
= array();
133 function clearState() {
134 $this->mOutput
= new ParserOutput
;
135 $this->mAutonumber
= 0;
136 $this->mLastSection
= '';
137 $this->mDTopen
= false;
138 $this->mVariables
= false;
139 $this->mIncludeCount
= array();
140 $this->mStripState
= array();
141 $this->mArgStack
= array();
142 $this->mInPre
= false;
143 $this->mInterwikiLinkHolders
= array();
144 $this->mLinkHolders
= array(
145 'namespaces' => array(),
147 'queries' => array(),
154 * First pass--just handle <nowiki> sections, pass the rest off
155 * to internalParse() which does all the real work.
158 * @param string $text Text we want to parse
159 * @param Title &$title A title object
160 * @param array $options
161 * @param boolean $linestart
162 * @param boolean $clearState
163 * @return ParserOutput a ParserOutput
165 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
166 global $wgUseTidy, $wgContLang, $wgCapitalLinks;
167 $fname = 'Parser::parse';
168 wfProfileIn( $fname );
174 $this->mOptions
= $options;
175 $this->mTitle
=& $title;
176 $this->mOutput
->mLcfirstTitle
= false;
177 $this->mOutputType
= OT_HTML
;
179 $this->mStripState
= NULL;
181 //$text = $this->strip( $text, $this->mStripState );
182 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
183 $x =& $this->mStripState
;
184 $text = $this->strip( $text, $x );
186 $text = $this->internalParse( $text );
188 // if the string __LCFIRST__ (make the first character of the title
189 // lower case) occurs in the HTML, set the mLcfirstTitle to true
190 $mw =& MagicWord
::get( MAG_LCFIRST
);
191 if( $mw->matchAndRemove( $text ) && $wgCapitalLinks ) {
193 $this->mOutput
->mLcfirstTitle
= true;
196 $text = $this->unstrip( $text, $this->mStripState
);
198 # Clean up special characters, only run once, next-to-last before doBlockLevels
200 # french spaces, last one Guillemet-left
201 # only if there is something before the space
202 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
203 # french spaces, Guillemet-right
204 '/(\\302\\253) /' => '\\1 ',
205 '/<hr *>/i' => '<hr />',
206 '/<br *>/i' => '<br />',
207 '/<center *>/i' => '<div class="center">',
208 '/<\\/center *>/i' => '</div>',
210 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
213 $text = $this->doBlockLevels( $text, $linestart );
215 $this->replaceLinkHolders( $text );
217 $dashReplace = array(
218 '/ - /' => " – ", # N dash
219 '/(?<=[\d])-(?=[\d])/' => "–", # N dash between numbers
220 '/ -- /' => " — " # M dash
222 $text = preg_replace( array_keys($dashReplace), array_values($dashReplace), $text );
224 # the position of the convert() call should not be changed. it
225 # assumes that the links are all replaces and the only thing left
226 # is the <nowiki> mark.
227 $text = $wgContLang->convert($text);
228 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
230 $text = $this->unstripNoWiki( $text, $this->mStripState
);
232 $text = Sanitizer
::normalizeCharReferences( $text );
235 $text = Parser
::tidy($text);
238 $this->mOutput
->setText( $text );
239 wfProfileOut( $fname );
240 return $this->mOutput
;
244 * Get a random string
249 function getRandomString() {
250 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
254 * Replaces all occurrences of <$tag>content</$tag> in the text
255 * with a random marker and returns the new text. the output parameter
256 * $content will be an associative array filled with data on the form
257 * $unique_marker => content.
259 * If $content is already set, the additional entries will be appended
260 * If $tag is set to STRIP_COMMENTS, the function will extract
261 * <!-- HTML comments -->
266 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
267 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
274 while ( '' != $text ) {
275 if($tag==STRIP_COMMENTS
) {
276 $p = preg_split( '/<!--/', $text, 2 );
278 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
281 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
284 if($tag==STRIP_COMMENTS
) {
285 $q = preg_split( '/-->/i', $p[1], 2 );
287 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
289 $marker = $rnd . sprintf('%08X', $n++
);
290 $content[$marker] = $q[0];
291 $stripped .= $marker;
299 * Strips and renders nowiki, pre, math, hiero
300 * If $render is set, performs necessary rendering operations on plugins
301 * Returns the text, and fills an array with data needed in unstrip()
302 * If the $state is already a valid strip state, it adds to the state
304 * @param bool $stripcomments when set, HTML comments <!-- like this -->
305 * will be stripped in addition to other tags. This is important
306 * for section editing, where these comments cause confusion when
307 * counting the sections in the wikisource
311 function strip( $text, &$state, $stripcomments = false ) {
312 $render = ($this->mOutputType
== OT_HTML
);
313 $html_content = array();
314 $nowiki_content = array();
315 $math_content = array();
316 $pre_content = array();
317 $comment_content = array();
318 $ext_content = array();
319 $gallery_content = array();
321 # Replace any instances of the placeholders
322 $uniq_prefix = UNIQ_PREFIX
;
323 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
326 global $wgRawHtml, $wgWhitelistEdit;
327 if( $wgRawHtml && $wgWhitelistEdit ) {
328 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
329 foreach( $html_content as $marker => $content ) {
331 # Raw and unchecked for validity.
332 $html_content[$marker] = $content;
334 $html_content[$marker] = '<html>'.$content.'</html>';
340 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
341 foreach( $nowiki_content as $marker => $content ) {
343 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
345 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
350 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
351 foreach( $math_content as $marker => $content ){
353 if( $this->mOptions
->getUseTeX() ) {
354 $math_content[$marker] = renderMath( $content );
356 $math_content[$marker] = '<math>'.$content.'<math>';
359 $math_content[$marker] = '<math>'.$content.'</math>';
364 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
365 foreach( $pre_content as $marker => $content ){
367 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
369 $pre_content[$marker] = '<pre>'.$content.'</pre>';
374 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
375 foreach( $gallery_content as $marker => $content ) {
376 require_once( 'ImageGallery.php' );
378 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
380 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
386 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
387 foreach( $comment_content as $marker => $content ){
388 $comment_content[$marker] = '<!--'.$content.'-->';
393 foreach ( $this->mTagHooks
as $tag => $callback ) {
394 $ext_content[$tag] = array();
395 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
396 foreach( $ext_content[$tag] as $marker => $content ) {
398 $ext_content[$tag][$marker] = $callback( $content );
400 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
405 # Merge state with the pre-existing state, if there is one
407 $state['html'] = $state['html'] +
$html_content;
408 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
409 $state['math'] = $state['math'] +
$math_content;
410 $state['pre'] = $state['pre'] +
$pre_content;
411 $state['comment'] = $state['comment'] +
$comment_content;
412 $state['gallery'] = $state['gallery'] +
$gallery_content;
414 foreach( $ext_content as $tag => $array ) {
415 if ( array_key_exists( $tag, $state ) ) {
416 $state[$tag] = $state[$tag] +
$array;
421 'html' => $html_content,
422 'nowiki' => $nowiki_content,
423 'math' => $math_content,
424 'pre' => $pre_content,
425 'comment' => $comment_content,
426 'gallery' => $gallery_content,
433 * restores pre, math, and hiero removed by strip()
435 * always call unstripNoWiki() after this one
438 function unstrip( $text, &$state ) {
439 # Must expand in reverse order, otherwise nested tags will be corrupted
440 $contentDict = end( $state );
441 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
442 if( key($state) != 'nowiki' && key($state) != 'html') {
443 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
444 $text = str_replace( key( $contentDict ), $content, $text );
453 * always call this after unstrip() to preserve the order
457 function unstripNoWiki( $text, &$state ) {
458 # Must expand in reverse order, otherwise nested tags will be corrupted
459 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
460 $text = str_replace( key( $state['nowiki'] ), $content, $text );
465 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
466 $text = str_replace( key( $state['html'] ), $content, $text );
474 * Add an item to the strip state
475 * Returns the unique tag which must be inserted into the stripped text
476 * The tag will be replaced with the original text in unstrip()
480 function insertStripItem( $text, &$state ) {
481 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
490 $state['item'][$rnd] = $text;
495 * Interface with html tidy, used if $wgUseTidy = true.
496 * If tidy isn't able to correct the markup, the original will be
497 * returned in all its glory with a warning comment appended.
499 * Either the external tidy program or the in-process tidy extension
500 * will be used depending on availability. Override the default
501 * $wgTidyInternal setting to disable the internal if it's not working.
503 * @param string $text Hideous HTML input
504 * @return string Corrected HTML output
508 function tidy( $text ) {
509 global $wgTidyInternal;
510 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
511 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
512 '<head><title>test</title></head><body>'.$text.'</body></html>';
513 if( $wgTidyInternal ) {
514 $correctedtext = Parser
::internalTidy( $wrappedtext );
516 $correctedtext = Parser
::externalTidy( $wrappedtext );
518 if( is_null( $correctedtext ) ) {
519 wfDebug( "Tidy error detected!\n" );
520 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
522 return $correctedtext;
526 * Spawn an external HTML tidy process and get corrected markup back from it.
531 function externalTidy( $text ) {
532 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
533 $fname = 'Parser::externalTidy';
534 wfProfileIn( $fname );
539 $descriptorspec = array(
540 0 => array('pipe', 'r'),
541 1 => array('pipe', 'w'),
542 2 => array('file', '/dev/null', 'a')
545 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
546 if (is_resource($process)) {
547 fwrite($pipes[0], $text);
549 while (!feof($pipes[1])) {
550 $cleansource .= fgets($pipes[1], 1024);
553 proc_close($process);
556 wfProfileOut( $fname );
558 if( $cleansource == '' && $text != '') {
559 // Some kind of error happened, so we couldn't get the corrected text.
560 // Just give up; we'll use the source text and append a warning.
568 * Use the HTML tidy PECL extension to use the tidy library in-process,
569 * saving the overhead of spawning a new process. Currently written to
570 * the PHP 4.3.x version of the extension, may not work on PHP 5.
572 * 'pear install tidy' should be able to compile the extension module.
577 function internalTidy( $text ) {
579 $fname = 'Parser::internalTidy';
580 wfProfileIn( $fname );
582 tidy_load_config( $wgTidyConf );
583 tidy_set_encoding( 'utf8' );
584 tidy_parse_string( $text );
586 if( tidy_get_status() == 2 ) {
587 // 2 is magic number for fatal error
588 // http://www.php.net/manual/en/function.tidy-get-status.php
591 $cleansource = tidy_get_output();
593 wfProfileOut( $fname );
598 * parse the wiki syntax used to render tables
602 function doTableStuff ( $t ) {
603 $fname = 'Parser::doTableStuff';
604 wfProfileIn( $fname );
606 $t = explode ( "\n" , $t ) ;
607 $td = array () ; # Is currently a td tag open?
608 $ltd = array () ; # Was it TD or TH?
609 $tr = array () ; # Is currently a tr tag open?
610 $ltr = array () ; # tr attributes
611 $indent_level = 0; # indent level of the table
612 foreach ( $t AS $k => $x )
615 $fc = substr ( $x , 0 , 1 ) ;
616 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
617 $indent_level = strlen( $matches[1] );
618 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
619 '<table' . Sanitizer
::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
620 array_push ( $td , false ) ;
621 array_push ( $ltd , '' ) ;
622 array_push ( $tr , false ) ;
623 array_push ( $ltr , '' ) ;
625 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
626 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
627 $z = "</table>" . substr ( $x , 2);
628 $l = array_pop ( $ltd ) ;
629 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
630 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
632 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
634 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
635 $x = substr ( $x , 1 ) ;
636 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
638 $l = array_pop ( $ltd ) ;
639 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
640 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
643 array_push ( $tr , false ) ;
644 array_push ( $td , false ) ;
645 array_push ( $ltd , '' ) ;
646 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $x, 'tr' ) ) ;
648 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
650 if ( '|+' == substr ( $x , 0 , 2 ) ) {
652 $x = substr ( $x , 1 ) ;
654 $after = substr ( $x , 1 ) ;
655 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
656 $after = explode ( '||' , $after ) ;
659 # Loop through each table cell
660 foreach ( $after AS $theline )
665 $tra = array_pop ( $ltr ) ;
666 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
667 array_push ( $tr , true ) ;
668 array_push ( $ltr , '' ) ;
671 $l = array_pop ( $ltd ) ;
672 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
673 if ( $fc == '|' ) $l = 'td' ;
674 else if ( $fc == '!' ) $l = 'th' ;
675 else if ( $fc == '+' ) $l = 'caption' ;
677 array_push ( $ltd , $l ) ;
680 $y = explode ( '|' , $theline , 2 ) ;
681 # Note that a '|' inside an invalid link should not
682 # be mistaken as delimiting cell parameters
683 if ( strpos( $y[0], '[[' ) !== false ) {
684 $y = array ($theline);
686 if ( count ( $y ) == 1 )
687 $y = "{$z}<{$l}>{$y[0]}" ;
688 else $y = $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($y[0], $l).">{$y[1]}" ;
690 array_push ( $td , true ) ;
695 # Closing open td, tr && table
696 while ( count ( $td ) > 0 )
698 if ( array_pop ( $td ) ) $t[] = '</td>' ;
699 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
703 $t = implode ( "\n" , $t ) ;
704 wfProfileOut( $fname );
709 * Helper function for parse() that transforms wiki markup into
710 * HTML. Only called for $mOutputType == OT_HTML.
714 function internalParse( $text ) {
718 $fname = 'Parser::internalParse';
719 wfProfileIn( $fname );
721 $text = Sanitizer
::removeHTMLtags( $text );
722 $text = $this->replaceVariables( $text, $args );
724 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
726 $text = $this->doHeadings( $text );
727 if($this->mOptions
->getUseDynamicDates()) {
728 $df =& DateFormatter
::getInstance();
729 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
731 $text = $this->doAllQuotes( $text );
732 $text = $this->replaceInternalLinks( $text );
733 $text = $this->replaceExternalLinks( $text );
735 # replaceInternalLinks may sometimes leave behind
736 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
737 $text = str_replace("http-noparse://","http://",$text);
739 $text = $this->doMagicLinks( $text );
740 $text = $this->doTableStuff( $text );
741 $text = $this->formatHeadings( $text, $isMain );
743 wfProfileOut( $fname );
748 * Replace special strings like "ISBN xxx" and "RFC xxx" with
749 * magic external links.
753 function &doMagicLinks( &$text ) {
754 $text = $this->magicISBN( $text );
755 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
756 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
761 * Parse ^^ tokens and return html
765 function doExponent( $text ) {
766 $fname = 'Parser::doExponent';
767 wfProfileIn( $fname );
768 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
769 wfProfileOut( $fname );
774 * Parse headers and return html
778 function doHeadings( $text ) {
779 $fname = 'Parser::doHeadings';
780 wfProfileIn( $fname );
781 for ( $i = 6; $i >= 1; --$i ) {
782 $h = substr( '======', 0, $i );
783 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
784 "<h{$i}>\\1</h{$i}>\\2", $text );
786 wfProfileOut( $fname );
791 * Replace single quotes with HTML markup
793 * @return string the altered text
795 function doAllQuotes( $text ) {
796 $fname = 'Parser::doAllQuotes';
797 wfProfileIn( $fname );
799 $lines = explode( "\n", $text );
800 foreach ( $lines as $line ) {
801 $outtext .= $this->doQuotes ( $line ) . "\n";
803 $outtext = substr($outtext, 0,-1);
804 wfProfileOut( $fname );
809 * Helper function for doAllQuotes()
812 function doQuotes( $text ) {
813 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
814 if ( count( $arr ) == 1 )
818 # First, do some preliminary work. This may shift some apostrophes from
819 # being mark-up to being text. It also counts the number of occurrences
820 # of bold and italics mark-ups.
824 foreach ( $arr as $r )
826 if ( ( $i %
2 ) == 1 )
828 # If there are ever four apostrophes, assume the first is supposed to
829 # be text, and the remaining three constitute mark-up for bold text.
830 if ( strlen( $arr[$i] ) == 4 )
835 # If there are more than 5 apostrophes in a row, assume they're all
836 # text except for the last 5.
837 else if ( strlen( $arr[$i] ) > 5 )
839 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
842 # Count the number of occurrences of bold and italics mark-ups.
843 # We are not counting sequences of five apostrophes.
844 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
845 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
846 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
851 # If there is an odd number of both bold and italics, it is likely
852 # that one of the bold ones was meant to be an apostrophe followed
853 # by italics. Which one we cannot know for certain, but it is more
854 # likely to be one that has a single-letter word before it.
855 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
858 $firstsingleletterword = -1;
859 $firstmultiletterword = -1;
861 foreach ( $arr as $r )
863 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
865 $x1 = substr ($arr[$i-1], -1);
866 $x2 = substr ($arr[$i-1], -2, 1);
868 if ($firstspace == -1) $firstspace = $i;
869 } else if ($x2 == ' ') {
870 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
872 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
878 # If there is a single-letter word, use it!
879 if ($firstsingleletterword > -1)
881 $arr [ $firstsingleletterword ] = "''";
882 $arr [ $firstsingleletterword-1 ] .= "'";
884 # If not, but there's a multi-letter word, use that one.
885 else if ($firstmultiletterword > -1)
887 $arr [ $firstmultiletterword ] = "''";
888 $arr [ $firstmultiletterword-1 ] .= "'";
890 # ... otherwise use the first one that has neither.
891 # (notice that it is possible for all three to be -1 if, for example,
892 # there is only one pentuple-apostrophe in the line)
893 else if ($firstspace > -1)
895 $arr [ $firstspace ] = "''";
896 $arr [ $firstspace-1 ] .= "'";
900 # Now let's actually convert our apostrophic mush to HTML!
909 if ($state == 'both')
916 if (strlen ($r) == 2)
919 { $output .= '</i>'; $state = ''; }
920 else if ($state == 'bi')
921 { $output .= '</i>'; $state = 'b'; }
922 else if ($state == 'ib')
923 { $output .= '</b></i><b>'; $state = 'b'; }
924 else if ($state == 'both')
925 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
926 else # $state can be 'b' or ''
927 { $output .= '<i>'; $state .= 'i'; }
929 else if (strlen ($r) == 3)
932 { $output .= '</b>'; $state = ''; }
933 else if ($state == 'bi')
934 { $output .= '</i></b><i>'; $state = 'i'; }
935 else if ($state == 'ib')
936 { $output .= '</b>'; $state = 'i'; }
937 else if ($state == 'both')
938 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
939 else # $state can be 'i' or ''
940 { $output .= '<b>'; $state .= 'b'; }
942 else if (strlen ($r) == 5)
945 { $output .= '</b><i>'; $state = 'i'; }
946 else if ($state == 'i')
947 { $output .= '</i><b>'; $state = 'b'; }
948 else if ($state == 'bi')
949 { $output .= '</i></b>'; $state = ''; }
950 else if ($state == 'ib')
951 { $output .= '</b></i>'; $state = ''; }
952 else if ($state == 'both')
953 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
954 else # ($state == '')
955 { $buffer = ''; $state = 'both'; }
960 # Now close all remaining tags. Notice that the order is important.
961 if ($state == 'b' ||
$state == 'ib')
963 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
967 if ($state == 'both')
968 $output .= '<b><i>'.$buffer.'</i></b>';
974 * Replace external links
976 * Note: this is all very hackish and the order of execution matters a lot.
977 * Make sure to run maintenance/parserTests.php if you change this code.
981 function replaceExternalLinks( $text ) {
983 $fname = 'Parser::replaceExternalLinks';
984 wfProfileIn( $fname );
986 $sk =& $this->mOptions
->getSkin();
988 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
990 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
993 while ( $i<count( $bits ) ) {
995 $protocol = $bits[$i++
];
997 $trail = $bits[$i++
];
999 # The characters '<' and '>' (which were escaped by
1000 # removeHTMLtags()) should not be included in
1001 # URLs, per RFC 2396.
1002 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1003 $text = substr($url, $m2[0][1]) . ' ' . $text;
1004 $url = substr($url, 0, $m2[0][1]);
1007 # If the link text is an image URL, replace it with an <img> tag
1008 # This happened by accident in the original parser, but some people used it extensively
1009 $img = $this->maybeMakeExternalImage( $text );
1010 if ( $img !== false ) {
1016 # Set linktype for CSS - if URL==text, link is essentially free
1017 $linktype = ($text == $url) ?
'free' : 'text';
1019 # No link text, e.g. [http://domain.tld/some.link]
1020 if ( $text == '' ) {
1021 # Autonumber if allowed
1022 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
1023 $text = '[' . ++
$this->mAutonumber
. ']';
1024 $linktype = 'autonumber';
1026 # Otherwise just use the URL
1027 $text = htmlspecialchars( $url );
1031 # Have link text, e.g. [http://domain.tld/some.link text]s
1033 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1036 $text = $wgContLang->markNoConversion($text);
1038 # Replace & from obsolete syntax with &.
1039 # All HTML entities will be escaped by makeExternalLink()
1040 # or maybeMakeExternalImage()
1041 $url = str_replace( '&', '&', $url );
1043 # Process the trail (i.e. everything after this link up until start of the next link),
1044 # replacing any non-bracketed links
1045 $trail = $this->replaceFreeExternalLinks( $trail );
1048 # Use the encoded URL
1049 # This means that users can paste URLs directly into the text
1050 # Funny characters like ö aren't valid in URLs anyway
1051 # This was changed in August 2004
1052 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1055 wfProfileOut( $fname );
1060 * Replace anything that looks like a URL with a link
1063 function replaceFreeExternalLinks( $text ) {
1065 $fname = 'Parser::replaceFreeExternalLinks';
1066 wfProfileIn( $fname );
1068 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS
.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1069 $s = array_shift( $bits );
1072 $sk =& $this->mOptions
->getSkin();
1074 while ( $i < count( $bits ) ){
1075 $protocol = $bits[$i++
];
1076 $remainder = $bits[$i++
];
1078 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1079 # Found some characters after the protocol that look promising
1080 $url = $protocol . $m[1];
1083 # The characters '<' and '>' (which were escaped by
1084 # removeHTMLtags()) should not be included in
1085 # URLs, per RFC 2396.
1086 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1087 $trail = substr($url, $m2[0][1]) . $trail;
1088 $url = substr($url, 0, $m2[0][1]);
1091 # Move trailing punctuation to $trail
1093 # If there is no left bracket, then consider right brackets fair game too
1094 if ( strpos( $url, '(' ) === false ) {
1098 $numSepChars = strspn( strrev( $url ), $sep );
1099 if ( $numSepChars ) {
1100 $trail = substr( $url, -$numSepChars ) . $trail;
1101 $url = substr( $url, 0, -$numSepChars );
1104 # Replace & from obsolete syntax with &.
1105 # All HTML entities will be escaped by makeExternalLink()
1106 # or maybeMakeExternalImage()
1107 $url = str_replace( '&', '&', $url );
1109 # Is this an external image?
1110 $text = $this->maybeMakeExternalImage( $url );
1111 if ( $text === false ) {
1112 # Not an image, make a link
1113 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1115 $s .= $text . $trail;
1117 $s .= $protocol . $remainder;
1125 * make an image if it's allowed
1128 function maybeMakeExternalImage( $url ) {
1129 $sk =& $this->mOptions
->getSkin();
1131 if ( $this->mOptions
->getAllowExternalImages() ) {
1132 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1134 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1141 * Process [[ ]] wikilinks
1145 function replaceInternalLinks( $s ) {
1146 global $wgContLang, $wgLinkCache;
1147 static $fname = 'Parser::replaceInternalLinks' ;
1149 wfProfileIn( $fname );
1151 wfProfileIn( $fname.'-setup' );
1153 # the % is needed to support urlencoded titles as well
1154 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1156 $sk =& $this->mOptions
->getSkin();
1158 #split the entire text string on occurences of [[
1159 $a = explode( '[[', ' ' . $s );
1160 #get the first element (all text up to first [[), and remove the space we added
1161 $s = array_shift( $a );
1162 $s = substr( $s, 1 );
1164 # Match a link having the form [[namespace:link|alternate]]trail
1166 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1167 # Match cases where there is no "]]", which might still be images
1168 static $e1_img = FALSE;
1169 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1170 # Match the end of a line for a word that's not followed by whitespace,
1171 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1172 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1174 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1176 if( is_null( $this->mTitle
) ) {
1177 wfDebugDieBacktrace( 'nooo' );
1179 $nottalk = !$this->mTitle
->isTalkPage();
1181 if ( $useLinkPrefixExtension ) {
1182 if ( preg_match( $e2, $s, $m ) ) {
1183 $first_prefix = $m[2];
1186 $first_prefix = false;
1192 $selflink = $this->mTitle
->getPrefixedText();
1193 wfProfileOut( $fname.'-setup' );
1195 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1196 $useSubpages = $this->areSubpagesAllowed();
1198 # Loop for each link
1199 for ($k = 0; isset( $a[$k] ); $k++
) {
1201 if ( $useLinkPrefixExtension ) {
1202 wfProfileIn( $fname.'-prefixhandling' );
1203 if ( preg_match( $e2, $s, $m ) ) {
1211 $prefix = $first_prefix;
1212 $first_prefix = false;
1214 wfProfileOut( $fname.'-prefixhandling' );
1217 $might_be_img = false;
1219 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1221 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1222 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1223 # the real problem is with the $e1 regex
1225 if (preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1226 $text .= ']'; # so that replaceExternalLinks($text) works later
1229 # fix up urlencoded title texts
1230 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1232 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1233 $might_be_img = true;
1235 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1237 } else { # Invalid form; output directly
1238 $s .= $prefix . '[[' . $line ;
1242 # Don't allow internal links to pages containing
1243 # PROTO: where PROTO is a valid URL protocol; these
1244 # should be external links.
1245 if (preg_match('/^(\b(?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1246 $s .= $prefix . '[[' . $line ;
1250 # Make subpage if necessary
1251 if( $useSubpages ) {
1252 $link = $this->maybeDoSubpageLink( $m[1], $text );
1257 $noforce = (substr($m[1], 0, 1) != ':');
1259 # Strip off leading ':'
1260 $link = substr($link, 1);
1263 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1265 $s .= $prefix . '[[' . $line;
1269 #check other language variants of the link
1270 #if the article does not exist
1271 if( $checkVariantLink
1272 && $nt->getArticleID() == 0 ) {
1273 $wgContLang->findVariantLink($link, $nt);
1276 $ns = $nt->getNamespace();
1277 $iw = $nt->getInterWiki();
1279 if ($might_be_img) { # if this is actually an invalid link
1280 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1282 while (isset ($a[$k+
1]) ) {
1283 #look at the next 'line' to see if we can close it there
1284 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1285 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1286 # the first ]] closes the inner link, the second the image
1288 $text .= '[[' . $m[1];
1291 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1292 #if there's exactly one ]] that's fine, we'll keep looking
1293 $text .= '[[' . $m[0];
1295 #if $next_line is invalid too, we need look no further
1296 $text .= '[[' . $next_line;
1301 # we couldn't find the end of this imageLink, so output it raw
1302 #but don't ignore what might be perfectly normal links in the text we've examined
1303 $text = $this->replaceInternalLinks($text);
1304 $s .= $prefix . '[[' . $link . '|' . $text;
1305 # note: no $trail, because without an end, there *is* no trail
1308 } else { #it's not an image, so output it raw
1309 $s .= $prefix . '[[' . $link . '|' . $text;
1310 # note: no $trail, because without an end, there *is* no trail
1315 $wasblank = ( '' == $text );
1316 if( $wasblank ) $text = $link;
1319 # Link not escaped by : , create the various objects
1323 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1324 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1325 $s = rtrim($s . "\n");
1326 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1330 if ( $ns == NS_IMAGE
) {
1331 wfProfileIn( "$fname-image" );
1332 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1333 # recursively parse links inside the image caption
1334 # actually, this will parse them in any other parameters, too,
1335 # but it might be hard to fix that, and it doesn't matter ATM
1336 $text = $this->replaceExternalLinks($text);
1337 $text = $this->replaceInternalLinks($text);
1339 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1340 $s .= $prefix . str_replace('http://', 'http-noparse://', $this->makeImage( $nt, $text ) ) . $trail;
1341 $wgLinkCache->addImageLinkObj( $nt );
1343 wfProfileOut( "$fname-image" );
1346 wfProfileOut( "$fname-image" );
1350 if ( $ns == NS_CATEGORY
) {
1351 wfProfileIn( "$fname-category" );
1352 $t = $wgContLang->convert($nt->getText());
1353 $s = rtrim($s . "\n"); # bug 87
1355 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1356 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1357 $wgLinkCache->resume();
1360 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1361 $sortkey = $this->mTitle
->getText();
1363 $sortkey = $this->mTitle
->getPrefixedText();
1368 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1369 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1370 $this->mOutput
->addCategoryLink( $t );
1373 * Strip the whitespace Category links produce, see bug 87
1374 * @todo We might want to use trim($tmp, "\n") here.
1376 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1378 wfProfileOut( "$fname-category" );
1383 if( ( $nt->getPrefixedText() === $selflink ) &&
1384 ( $nt->getFragment() === '' ) ) {
1385 # Self-links are handled specially; generally de-link and change to bold.
1386 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1390 # Special and Media are pseudo-namespaces; no pages actually exist in them
1391 if( $ns == NS_MEDIA
) {
1392 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1393 $wgLinkCache->addImageLinkObj( $nt );
1395 } elseif( $ns == NS_SPECIAL
) {
1396 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1399 if ( $nt->isAlwaysKnown() ) {
1400 $s .= $sk->makeKnownLinkObj( $nt, $text, '', $trail, $prefix );
1403 * Add a link placeholder
1404 * Later, this will be replaced by a real link, after the existence or
1405 * non-existence of all the links is known
1407 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1410 wfProfileOut( $fname );
1415 * Make a link placeholder. The text returned can be later resolved to a real link with
1416 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1417 * parsing of interwiki links, and secondly to allow all extistence checks and
1418 * article length checks (for stub links) to be bundled into a single query.
1421 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1422 if ( ! is_object($nt) ) {
1424 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1426 # Separate the link trail from the rest of the link
1427 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1429 if ( $nt->isExternal() ) {
1430 $iwRecord = array( $nt->getPrefixedDBkey(), $prefix.$text.$inside );
1431 $nr = array_push($this->mInterwikiLinkHolders
, $iwRecord);
1432 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1434 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1435 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1436 $this->mLinkHolders
['queries'][] = $query;
1437 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1438 $this->mLinkHolders
['titles'][] =& $nt;
1440 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1447 * Return true if subpage links should be expanded on this page.
1450 function areSubpagesAllowed() {
1451 # Some namespaces don't allow subpages
1452 global $wgNamespacesWithSubpages;
1453 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1457 * Handle link to subpage if necessary
1458 * @param string $target the source of the link
1459 * @param string &$text the link text, modified as necessary
1460 * @return string the full name of the link
1463 function maybeDoSubpageLink($target, &$text) {
1466 # :Foobar -- override special treatment of prefix (images, language links)
1467 # /Foobar -- convert to CurrentPage/Foobar
1468 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1469 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1470 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1472 $fname = 'Parser::maybeDoSubpageLink';
1473 wfProfileIn( $fname );
1474 $ret = $target; # default return value is no change
1476 # Some namespaces don't allow subpages,
1477 # so only perform processing if subpages are allowed
1478 if( $this->areSubpagesAllowed() ) {
1479 # Look at the first character
1480 if( $target != '' && $target{0} == '/' ) {
1481 # / at end means we don't want the slash to be shown
1482 if( substr( $target, -1, 1 ) == '/' ) {
1483 $target = substr( $target, 1, -1 );
1486 $noslash = substr( $target, 1 );
1489 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1490 if( '' === $text ) {
1492 } # this might be changed for ugliness reasons
1494 # check for .. subpage backlinks
1496 $nodotdot = $target;
1497 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1499 $nodotdot = substr( $nodotdot, 3 );
1501 if($dotdotcount > 0) {
1502 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1503 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1504 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1505 # / at the end means don't show full path
1506 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1507 $nodotdot = substr( $nodotdot, 0, -1 );
1508 if( '' === $text ) {
1512 $nodotdot = trim( $nodotdot );
1513 if( $nodotdot != '' ) {
1514 $ret .= '/' . $nodotdot;
1521 wfProfileOut( $fname );
1526 * Used by doBlockLevels()
1529 /* private */ function closeParagraph() {
1531 if ( '' != $this->mLastSection
) {
1532 $result = '</' . $this->mLastSection
. ">\n";
1534 $this->mInPre
= false;
1535 $this->mLastSection
= '';
1538 # getCommon() returns the length of the longest common substring
1539 # of both arguments, starting at the beginning of both.
1541 /* private */ function getCommon( $st1, $st2 ) {
1542 $fl = strlen( $st1 );
1543 $shorter = strlen( $st2 );
1544 if ( $fl < $shorter ) { $shorter = $fl; }
1546 for ( $i = 0; $i < $shorter; ++
$i ) {
1547 if ( $st1{$i} != $st2{$i} ) { break; }
1551 # These next three functions open, continue, and close the list
1552 # element appropriate to the prefix character passed into them.
1554 /* private */ function openList( $char ) {
1555 $result = $this->closeParagraph();
1557 if ( '*' == $char ) { $result .= '<ul><li>'; }
1558 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1559 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1560 else if ( ';' == $char ) {
1561 $result .= '<dl><dt>';
1562 $this->mDTopen
= true;
1564 else { $result = '<!-- ERR 1 -->'; }
1569 /* private */ function nextItem( $char ) {
1570 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1571 else if ( ':' == $char ||
';' == $char ) {
1573 if ( $this->mDTopen
) { $close = '</dt>'; }
1574 if ( ';' == $char ) {
1575 $this->mDTopen
= true;
1576 return $close . '<dt>';
1578 $this->mDTopen
= false;
1579 return $close . '<dd>';
1582 return '<!-- ERR 2 -->';
1585 /* private */ function closeList( $char ) {
1586 if ( '*' == $char ) { $text = '</li></ul>'; }
1587 else if ( '#' == $char ) { $text = '</li></ol>'; }
1588 else if ( ':' == $char ) {
1589 if ( $this->mDTopen
) {
1590 $this->mDTopen
= false;
1591 $text = '</dt></dl>';
1593 $text = '</dd></dl>';
1596 else { return '<!-- ERR 3 -->'; }
1602 * Make lists from lines starting with ':', '*', '#', etc.
1605 * @return string the lists rendered as HTML
1607 function doBlockLevels( $text, $linestart ) {
1608 $fname = 'Parser::doBlockLevels';
1609 wfProfileIn( $fname );
1611 # Parsing through the text line by line. The main thing
1612 # happening here is handling of block-level elements p, pre,
1613 # and making lists from lines starting with * # : etc.
1615 $textLines = explode( "\n", $text );
1617 $lastPrefix = $output = '';
1618 $this->mDTopen
= $inBlockElem = false;
1620 $paragraphStack = false;
1622 if ( !$linestart ) {
1623 $output .= array_shift( $textLines );
1625 foreach ( $textLines as $oLine ) {
1626 $lastPrefixLength = strlen( $lastPrefix );
1627 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1628 $preOpenMatch = preg_match('/<pre/i', $oLine );
1629 if ( !$this->mInPre
) {
1630 # Multiple prefixes may abut each other for nested lists.
1631 $prefixLength = strspn( $oLine, '*#:;' );
1632 $pref = substr( $oLine, 0, $prefixLength );
1635 $pref2 = str_replace( ';', ':', $pref );
1636 $t = substr( $oLine, $prefixLength );
1637 $this->mInPre
= !empty($preOpenMatch);
1639 # Don't interpret any other prefixes in preformatted text
1641 $pref = $pref2 = '';
1646 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1647 # Same as the last item, so no need to deal with nesting or opening stuff
1648 $output .= $this->nextItem( substr( $pref, -1 ) );
1649 $paragraphStack = false;
1651 if ( substr( $pref, -1 ) == ';') {
1652 # The one nasty exception: definition lists work like this:
1653 # ; title : definition text
1654 # So we check for : in the remainder text to split up the
1655 # title and definition, without b0rking links.
1657 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1659 $output .= $term . $this->nextItem( ':' );
1662 } elseif( $prefixLength ||
$lastPrefixLength ) {
1663 # Either open or close a level...
1664 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1665 $paragraphStack = false;
1667 while( $commonPrefixLength < $lastPrefixLength ) {
1668 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1669 --$lastPrefixLength;
1671 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1672 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1674 while ( $prefixLength > $commonPrefixLength ) {
1675 $char = substr( $pref, $commonPrefixLength, 1 );
1676 $output .= $this->openList( $char );
1678 if ( ';' == $char ) {
1679 # FIXME: This is dupe of code above
1680 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1682 $output .= $term . $this->nextItem( ':' );
1685 ++
$commonPrefixLength;
1687 $lastPrefix = $pref2;
1689 if( 0 == $prefixLength ) {
1690 wfProfileIn( "$fname-paragraph" );
1691 # No prefix (not in list)--go to paragraph mode
1692 $uniq_prefix = UNIQ_PREFIX
;
1693 // XXX: use a stack for nestable elements like span, table and div
1694 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1695 $closematch = preg_match(
1696 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1697 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1698 if ( $openmatch or $closematch ) {
1699 $paragraphStack = false;
1700 $output .= $this->closeParagraph();
1701 if($preOpenMatch and !$preCloseMatch) {
1702 $this->mInPre
= true;
1704 if ( $closematch ) {
1705 $inBlockElem = false;
1707 $inBlockElem = true;
1709 } else if ( !$inBlockElem && !$this->mInPre
) {
1710 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1712 if ($this->mLastSection
!= 'pre') {
1713 $paragraphStack = false;
1714 $output .= $this->closeParagraph().'<pre>';
1715 $this->mLastSection
= 'pre';
1717 $t = substr( $t, 1 );
1720 if ( '' == trim($t) ) {
1721 if ( $paragraphStack ) {
1722 $output .= $paragraphStack.'<br />';
1723 $paragraphStack = false;
1724 $this->mLastSection
= 'p';
1726 if ($this->mLastSection
!= 'p' ) {
1727 $output .= $this->closeParagraph();
1728 $this->mLastSection
= '';
1729 $paragraphStack = '<p>';
1731 $paragraphStack = '</p><p>';
1735 if ( $paragraphStack ) {
1736 $output .= $paragraphStack;
1737 $paragraphStack = false;
1738 $this->mLastSection
= 'p';
1739 } else if ($this->mLastSection
!= 'p') {
1740 $output .= $this->closeParagraph().'<p>';
1741 $this->mLastSection
= 'p';
1746 wfProfileOut( "$fname-paragraph" );
1748 if ($paragraphStack === false) {
1752 while ( $prefixLength ) {
1753 $output .= $this->closeList( $pref2{$prefixLength-1} );
1756 if ( '' != $this->mLastSection
) {
1757 $output .= '</' . $this->mLastSection
. '>';
1758 $this->mLastSection
= '';
1761 wfProfileOut( $fname );
1766 * Split up a string on ':', ignoring any occurences inside
1767 * <a>..</a> or <span>...</span>
1768 * @param string $str the string to split
1769 * @param string &$before set to everything before the ':'
1770 * @param string &$after set to everything after the ':'
1771 * return string the position of the ':', or false if none found
1773 function findColonNoLinks($str, &$before, &$after) {
1774 # I wonder if we should make this count all tags, not just <a>
1775 # and <span>. That would prevent us from matching a ':' that
1776 # comes in the middle of italics other such formatting....
1778 $fname = 'Parser::findColonNoLinks';
1779 wfProfileIn( $fname );
1782 $colon = strpos($str, ':', $pos);
1784 if ($colon !== false) {
1785 $before = substr($str, 0, $colon);
1786 $after = substr($str, $colon +
1);
1788 # Skip any ':' within <a> or <span> pairs
1789 $a = substr_count($before, '<a');
1790 $s = substr_count($before, '<span');
1791 $ca = substr_count($before, '</a>');
1792 $cs = substr_count($before, '</span>');
1794 if ($a <= $ca and $s <= $cs) {
1795 # Tags are balanced before ':'; ok
1800 } while ($colon !== false);
1801 wfProfileOut( $fname );
1806 * Return value of a magic variable (like PAGENAME)
1810 function getVariableValue( $index ) {
1811 global $wgContLang, $wgSitename, $wgServer, $wgArticle;
1814 * Some of these require message or data lookups and can be
1815 * expensive to check many times.
1817 static $varCache = array();
1818 if( isset( $varCache[$index] ) ) return $varCache[$index];
1821 case MAG_CURRENTMONTH
:
1822 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1823 case MAG_CURRENTMONTHNAME
:
1824 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1825 case MAG_CURRENTMONTHNAMEGEN
:
1826 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1827 case MAG_CURRENTMONTHABBREV
:
1828 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1829 case MAG_CURRENTDAY
:
1830 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1832 return $this->mTitle
->getText();
1834 return $this->mTitle
->getPartialURL();
1835 case MAG_REVISIONID
:
1836 return $wgArticle->getRevIdFetched();
1838 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1839 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1840 case MAG_CURRENTDAYNAME
:
1841 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1842 case MAG_CURRENTYEAR
:
1843 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1844 case MAG_CURRENTTIME
:
1845 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1846 case MAG_CURRENTWEEK
:
1847 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1848 case MAG_CURRENTDOW
:
1849 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1850 case MAG_NUMBEROFARTICLES
:
1851 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1862 * initialise the magic variables (like CURRENTMONTHNAME)
1866 function initialiseVariables() {
1867 $fname = 'Parser::initialiseVariables';
1868 wfProfileIn( $fname );
1869 global $wgVariableIDs;
1870 $this->mVariables
= array();
1871 foreach ( $wgVariableIDs as $id ) {
1872 $mw =& MagicWord
::get( $id );
1873 $mw->addToArray( $this->mVariables
, $id );
1875 wfProfileOut( $fname );
1879 * Replace magic variables, templates, and template arguments
1880 * with the appropriate text. Templates are substituted recursively,
1881 * taking care to avoid infinite loops.
1883 * Note that the substitution depends on value of $mOutputType:
1884 * OT_WIKI: only {{subst:}} templates
1885 * OT_MSG: only magic variables
1886 * OT_HTML: all templates and magic variables
1888 * @param string $tex The text to transform
1889 * @param array $args Key-value pairs representing template parameters to substitute
1892 function replaceVariables( $text, $args = array() ) {
1894 # Prevent too big inclusions
1895 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1899 $fname = 'Parser::replaceVariables';
1900 wfProfileIn( $fname );
1902 $titleChars = Title
::legalChars();
1904 # This function is called recursively. To keep track of arguments we need a stack:
1905 array_push( $this->mArgStack
, $args );
1907 # Variable substitution
1908 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1910 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1911 # Argument substitution
1912 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1914 # Template substitution
1915 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1916 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1918 array_pop( $this->mArgStack
);
1920 wfProfileOut( $fname );
1925 * Replace magic variables
1928 function variableSubstitution( $matches ) {
1929 $fname = 'parser::variableSubstitution';
1930 $varname = $matches[1];
1931 wfProfileIn( $fname );
1932 if ( !$this->mVariables
) {
1933 $this->initialiseVariables();
1936 if ( $this->mOutputType
== OT_WIKI
) {
1937 # Do only magic variables prefixed by SUBST
1938 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1939 if (!$mwSubst->matchStartAndRemove( $varname ))
1941 # Note that if we don't substitute the variable below,
1942 # we don't remove the {{subst:}} magic word, in case
1943 # it is a template rather than a magic variable.
1945 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
1946 $id = $this->mVariables
[$varname];
1947 $text = $this->getVariableValue( $id );
1948 $this->mOutput
->mContainsOldMagic
= true;
1950 $text = $matches[0];
1952 wfProfileOut( $fname );
1956 # Split template arguments
1957 function getTemplateArgs( $argsString ) {
1958 if ( $argsString === '' ) {
1962 $args = explode( '|', substr( $argsString, 1 ) );
1964 # If any of the arguments contains a '[[' but no ']]', it needs to be
1965 # merged with the next arg because the '|' character between belongs
1966 # to the link syntax and not the template parameter syntax.
1967 $argc = count($args);
1969 for ( $i = 0; $i < $argc-1; $i++
) {
1970 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1971 $args[$i] .= '|'.$args[$i+
1];
1972 array_splice($args, $i+
1, 1);
1982 * Return the text of a template, after recursively
1983 * replacing any variables or templates within the template.
1985 * @param array $matches The parts of the template
1986 * $matches[1]: the title, i.e. the part before the |
1987 * $matches[2]: the parameters (including a leading |), if any
1988 * @return string the text of the template
1991 function braceSubstitution( $matches ) {
1992 global $wgLinkCache, $wgContLang;
1993 $fname = 'Parser::braceSubstitution';
1994 wfProfileIn( $fname );
2002 # Need to know if the template comes at the start of a line,
2003 # to treat the beginning of the template like the beginning
2004 # of a line for tables and block-level elements.
2005 $linestart = $matches[1];
2007 # $part1 is the bit before the first |, and must contain only title characters
2008 # $args is a list of arguments, starting from index 0, not including $part1
2010 $part1 = $matches[2];
2011 # If the third subpattern matched anything, it will start with |
2013 $args = $this->getTemplateArgs($matches[3]);
2014 $argc = count( $args );
2016 # Don't parse {{{}}} because that's only for template arguments
2017 if ( $linestart === '{' ) {
2018 $text = $matches[0];
2025 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2026 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2027 # One of two possibilities is true:
2028 # 1) Found SUBST but not in the PST phase
2029 # 2) Didn't find SUBST and in the PST phase
2030 # In either case, return without further processing
2031 $text = $matches[0];
2037 # MSG, MSGNW and INT
2040 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2041 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2045 # Check if it is an internal message
2046 $mwInt =& MagicWord
::get( MAG_INT
);
2047 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2048 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2049 $text = $linestart . wfMsgReal( $part1, $args, true );
2057 # Check for NS: (namespace expansion)
2058 $mwNs = MagicWord
::get( MAG_NS
);
2059 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2060 if ( intval( $part1 ) ) {
2061 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2064 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2065 if ( !is_null( $index ) ) {
2066 $text = $linestart . $wgContLang->getNsText( $index );
2073 # LOCALURL and LOCALURLE
2075 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
2076 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
2078 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2079 $func = 'getLocalURL';
2080 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2081 $func = 'escapeLocalURL';
2086 if ( $func !== '' ) {
2087 $title = Title
::newFromText( $part1 );
2088 if ( !is_null( $title ) ) {
2090 $text = $linestart . $title->$func( $args[0] );
2092 $text = $linestart . $title->$func();
2100 if ( !$found && $argc == 1 ) {
2101 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2102 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2103 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2108 # Template table test
2110 # Did we encounter this template already? If yes, it is in the cache
2111 # and we need to check for loops.
2112 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2115 # Infinite loop test
2116 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2119 $text = $linestart .
2121 '<!-- WARNING: template loop detected -->';
2122 wfDebug( "$fname: template loop broken at '$part1'\n" );
2124 # set $text to cached message.
2125 $text = $linestart . $this->mTemplates
[$part1];
2129 # Load from database
2130 $itcamefromthedatabase = false;
2131 $lastPathLevel = $this->mTemplatePath
;
2134 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2135 if ($subpage !== '') {
2136 $ns = $this->mTitle
->getNamespace();
2138 $title = Title
::newFromText( $part1, $ns );
2139 if ( !is_null( $title ) && !$title->isExternal() ) {
2140 # Check for excessive inclusion
2141 $dbk = $title->getPrefixedDBkey();
2142 if ( $this->incrementIncludeCount( $dbk ) ) {
2143 # This should never be reached.
2144 $article = new Article( $title );
2145 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2146 if ( $articleContent !== false ) {
2148 $text = $linestart . $articleContent;
2149 $itcamefromthedatabase = true;
2153 # If the title is valid but undisplayable, make a link to it
2154 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2155 $text = $linestart . '[['.$title->getPrefixedText().']]';
2159 # Template cache array insertion
2161 $this->mTemplates
[$part1] = $text;
2166 # Recursive parsing, escaping and link table handling
2167 # Only for HTML output
2168 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2169 $text = wfEscapeWikiText( $text );
2170 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2171 # Clean up argument array
2172 $assocArgs = array();
2174 foreach( $args as $arg ) {
2175 $eqpos = strpos( $arg, '=' );
2176 if ( $eqpos === false ) {
2177 $assocArgs[$index++
] = $arg;
2179 $name = trim( substr( $arg, 0, $eqpos ) );
2180 $value = trim( substr( $arg, $eqpos+
1 ) );
2181 if ( $value === false ) {
2184 if ( $name !== false ) {
2185 $assocArgs[$name] = $value;
2190 # Add a new element to the templace recursion path
2191 $this->mTemplatePath
[$part1] = 1;
2193 if( $this->mOutputType
== OT_HTML
) {
2194 $text = $this->strip( $text, $this->mStripState
);
2195 $text = Sanitizer
::removeHTMLtags( $text );
2197 $text = $this->replaceVariables( $text, $assocArgs );
2199 # Resume the link cache and register the inclusion as a link
2200 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2201 $wgLinkCache->addLinkObj( $title );
2204 # If the template begins with a table or block-level
2205 # element, it should be treated as beginning a new line.
2206 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2207 $text = "\n" . $text;
2210 # Prune lower levels off the recursion check path
2211 $this->mTemplatePath
= $lastPathLevel;
2214 wfProfileOut( $fname );
2217 # replace ==section headers==
2218 # XXX this needs to go away once we have a better parser.
2219 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
2220 if( !is_null( $title ) )
2221 $encodedname = base64_encode($title->getPrefixedDBkey());
2223 $encodedname = base64_encode("");
2224 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2225 PREG_SPLIT_DELIM_CAPTURE
);
2228 for( $i = 0; $i < count($m); $i +
= 2 ) {
2230 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2232 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2236 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2237 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2238 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2244 # Prune lower levels off the recursion check path
2245 $this->mTemplatePath
= $lastPathLevel;
2248 wfProfileOut( $fname );
2251 wfProfileOut( $fname );
2257 * Triple brace replacement -- used for template arguments
2260 function argSubstitution( $matches ) {
2261 $arg = trim( $matches[1] );
2262 $text = $matches[0];
2263 $inputArgs = end( $this->mArgStack
);
2265 if ( array_key_exists( $arg, $inputArgs ) ) {
2266 $text = $inputArgs[$arg];
2273 * Returns true if the function is allowed to include this entity
2276 function incrementIncludeCount( $dbk ) {
2277 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2278 $this->mIncludeCount
[$dbk] = 0;
2280 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2288 * This function accomplishes several tasks:
2289 * 1) Auto-number headings if that option is enabled
2290 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2291 * 3) Add a Table of contents on the top for users who have enabled the option
2292 * 4) Auto-anchor headings
2294 * It loops through all headlines, collects the necessary data, then splits up the
2295 * string and re-inserts the newly formatted headlines.
2297 * @param string $text
2298 * @param boolean $isMain
2301 function formatHeadings( $text, $isMain=true ) {
2302 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2304 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2306 $forceTocHere = false;
2307 if( !$this->mTitle
->userCanEdit() ) {
2310 $showEditLink = $this->mOptions
->getEditSection();
2313 # Inhibit editsection links if requested in the page
2314 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2315 if( $esw->matchAndRemove( $text ) ) {
2318 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2320 $mw =& MagicWord
::get( MAG_NOTOC
);
2321 if( $mw->matchAndRemove( $text ) ) {
2325 # Get all headlines for numbering them and adding funky stuff like [edit]
2326 # links - this is for later, but we need the number of headlines right now
2327 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2329 # if there are fewer than 4 headlines in the article, do not show TOC
2330 if( $numMatches < 4 ) {
2334 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2335 # override above conditions and always show TOC at that place
2337 $mw =& MagicWord
::get( MAG_TOC
);
2338 if($mw->match( $text ) ) {
2340 $forceTocHere = true;
2342 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2343 # override above conditions and always show TOC above first header
2344 $mw =& MagicWord
::get( MAG_FORCETOC
);
2345 if ($mw->matchAndRemove( $text ) ) {
2350 # Never ever show TOC if no headers
2351 if( $numMatches < 1 ) {
2355 # We need this to perform operations on the HTML
2356 $sk =& $this->mOptions
->getSkin();
2360 $sectionCount = 0; # headlineCount excluding template sections
2362 # Ugh .. the TOC should have neat indentation levels which can be
2363 # passed to the skin functions. These are determined here
2367 $sublevelCount = array();
2368 $levelCount = array();
2375 foreach( $matches[3] as $headline ) {
2377 $templatetitle = '';
2378 $templatesection = 0;
2381 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2383 $templatetitle = base64_decode($mat[1]);
2384 $templatesection = 1 +
(int)base64_decode($mat[2]);
2385 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2389 $prevlevel = $level;
2390 $prevtoclevel = $toclevel;
2392 $level = $matches[1][$headlineCount];
2394 if( $doNumberHeadings ||
$doShowToc ) {
2396 if ( $level > $prevlevel ) {
2397 # Increase TOC level
2399 $sublevelCount[$toclevel] = 0;
2400 $toc .= $sk->tocIndent();
2402 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2403 # Decrease TOC level, find level to jump to
2405 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2406 # Can only go down to level 1
2409 for ($i = $toclevel; $i > 0; $i--) {
2410 if ( $levelCount[$i] == $level ) {
2411 # Found last matching level
2415 elseif ( $levelCount[$i] < $level ) {
2416 # Found first matching level below current level
2423 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2426 # No change in level, end TOC line
2427 $toc .= $sk->tocLineEnd();
2430 $levelCount[$toclevel] = $level;
2432 # count number of headlines for each level
2433 @$sublevelCount[$toclevel]++
;
2435 for( $i = 1; $i <= $toclevel; $i++
) {
2436 if( !empty( $sublevelCount[$i] ) ) {
2440 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2446 # The canonized header is a version of the header text safe to use for links
2447 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2448 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2449 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2451 # Remove link placeholders by the link text.
2452 # <!--LINK number-->
2454 # link text with suffix
2455 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2456 "\$this->mLinkHolders['texts'][\$1]",
2457 $canonized_headline );
2458 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2459 "\$this->mInterwikiLinkHolders[\$1][1]",
2460 $canonized_headline );
2463 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2464 $tocline = trim( $canonized_headline );
2465 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2466 $replacearray = array(
2470 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2471 $refers[$headlineCount] = $canonized_headline;
2473 # count how many in assoc. array so we can track dupes in anchors
2474 @$refers[$canonized_headline]++
;
2475 $refcount[$headlineCount]=$refers[$canonized_headline];
2477 # Don't number the heading if it is the only one (looks silly)
2478 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2479 # the two are different if the line contains a link
2480 $headline=$numbering . ' ' . $headline;
2483 # Create the anchor for linking from the TOC to the section
2484 $anchor = $canonized_headline;
2485 if($refcount[$headlineCount] > 1 ) {
2486 $anchor .= '_' . $refcount[$headlineCount];
2488 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2489 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2491 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2492 if ( empty( $head[$headlineCount] ) ) {
2493 $head[$headlineCount] = '';
2496 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2498 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2501 # give headline the correct <h#> tag
2502 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2510 $toc .= $sk->tocUnindent( $toclevel - 1 );
2511 $toc = $sk->tocList( $toc );
2514 # split up and insert constructed headlines
2516 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2519 foreach( $blocks as $block ) {
2520 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2521 # This is the [edit] link that appears for the top block of text when
2522 # section editing is enabled
2524 # Disabled because it broke block formatting
2525 # For example, a bullet point in the top line
2526 # $full .= $sk->editSectionLink(0);
2529 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2530 # Top anchor now in skin
2534 if( !empty( $head[$i] ) ) {
2540 $mw =& MagicWord
::get( MAG_TOC
);
2541 return $mw->replace( $toc, $full );
2548 * Return an HTML link for the "ISBN 123456" text
2551 function magicISBN( $text ) {
2552 $fname = 'Parser::magicISBN';
2553 wfProfileIn( $fname );
2555 $a = split( 'ISBN ', ' '.$text );
2556 if ( count ( $a ) < 2 ) {
2557 wfProfileOut( $fname );
2560 $text = substr( array_shift( $a ), 1);
2561 $valid = '0123456789-Xx';
2563 foreach ( $a as $x ) {
2564 $isbn = $blank = '' ;
2565 while ( ' ' == $x{0} ) {
2567 $x = substr( $x, 1 );
2569 if ( $x == '' ) { # blank isbn
2570 $text .= "ISBN $blank";
2573 while ( strstr( $valid, $x{0} ) != false ) {
2575 $x = substr( $x, 1 );
2577 $num = str_replace( '-', '', $isbn );
2578 $num = str_replace( ' ', '', $num );
2579 $num = str_replace( 'x', 'X', $num );
2582 $text .= "ISBN $blank$x";
2584 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2585 $text .= '<a href="' .
2586 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2587 "\" class=\"internal\">ISBN $isbn</a>";
2591 wfProfileOut( $fname );
2596 * Return an HTML link for the "RFC 1234" text
2599 * @param string $text Text to be processed
2600 * @param string $keyword Magic keyword to use (default RFC)
2601 * @param string $urlmsg Interface message to use (default rfcurl)
2604 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2606 $valid = '0123456789';
2609 $a = split( $keyword, ' '.$text );
2610 if ( count ( $a ) < 2 ) {
2613 $text = substr( array_shift( $a ), 1);
2615 /* Check if keyword is preceed by [[.
2616 * This test is made here cause of the array_shift above
2617 * that prevent the test to be done in the foreach.
2619 if ( substr( $text, -2 ) == '[[' ) {
2623 foreach ( $a as $x ) {
2624 /* token might be empty if we have RFC RFC 1234 */
2632 /** remove and save whitespaces in $blank */
2633 while ( $x{0} == ' ' ) {
2635 $x = substr( $x, 1 );
2638 /** remove and save the rfc number in $id */
2639 while ( strstr( $valid, $x{0} ) != false ) {
2641 $x = substr( $x, 1 );
2645 /* call back stripped spaces*/
2646 $text .= $keyword.$blank.$x;
2647 } elseif( $internal ) {
2649 $text .= $keyword.$id.$x;
2651 /* build the external link*/
2652 $url = wfMsg( $urlmsg, $id);
2653 $sk =& $this->mOptions
->getSkin();
2654 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2655 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2658 /* Check if the next RFC keyword is preceed by [[ */
2659 $internal = ( substr($x,-2) == '[[' );
2665 * Transform wiki markup when saving a page by doing \r\n -> \n
2666 * conversion, substitting signatures, {{subst:}} templates, etc.
2668 * @param string $text the text to transform
2669 * @param Title &$title the Title object for the current article
2670 * @param User &$user the User object describing the current user
2671 * @param ParserOptions $options parsing options
2672 * @param bool $clearState whether to clear the parser state first
2673 * @return string the altered wiki markup
2676 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2677 $this->mOptions
= $options;
2678 $this->mTitle
=& $title;
2679 $this->mOutputType
= OT_WIKI
;
2681 if ( $clearState ) {
2682 $this->clearState();
2685 $stripState = false;
2689 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2690 $text = $this->strip( $text, $stripState, false );
2691 $text = $this->pstPass2( $text, $user );
2692 $text = $this->unstrip( $text, $stripState );
2693 $text = $this->unstripNoWiki( $text, $stripState );
2698 * Pre-save transform helper function
2701 function pstPass2( $text, &$user ) {
2702 global $wgContLang, $wgLocaltimezone;
2704 # Variable replacement
2705 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2706 $text = $this->replaceVariables( $text );
2710 $n = $user->getName();
2711 $k = $user->getOption( 'nickname' );
2712 if ( '' == $k ) { $k = $n; }
2713 if ( isset( $wgLocaltimezone ) ) {
2714 $oldtz = getenv( 'TZ' );
2715 putenv( 'TZ='.$wgLocaltimezone );
2718 /* Note: This is the timestamp saved as hardcoded wikitext to
2719 * the database, we use $wgContLang here in order to give
2720 * everyone the same signiture and use the default one rather
2721 * than the one selected in each users preferences.
2723 $d = $wgContLang->timeanddate( wfTimestampNow(), false, false) .
2724 ' (' . date( 'T' ) . ')';
2725 if ( isset( $wgLocaltimezone ) ) {
2726 putenv( 'TZ='.$oldtz );
2729 if( $user->getOption( 'fancysig' ) ) {
2732 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2734 $text = preg_replace( '/~~~~~/', $d, $text );
2735 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2736 $text = preg_replace( '/~~~/', $sigText, $text );
2738 # Context links: [[|name]] and [[name (context)|]]
2740 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2741 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2742 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2743 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2745 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2746 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2747 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2748 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2750 $t = $this->mTitle
->getText();
2751 if ( preg_match( $conpat, $t, $m ) ) {
2754 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2755 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2756 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2758 if ( '' == $context ) {
2759 $text = preg_replace( $p2, '[[\\1]]', $text );
2761 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2764 # Trim trailing whitespace
2765 # MAG_END (__END__) tag allows for trailing
2766 # whitespace to be deliberately included
2767 $text = rtrim( $text );
2768 $mw =& MagicWord
::get( MAG_END
);
2769 $mw->matchAndRemove( $text );
2775 * Set up some variables which are usually set up in parse()
2776 * so that an external function can call some class members with confidence
2779 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2780 $this->mTitle
=& $title;
2781 $this->mOptions
= $options;
2782 $this->mOutputType
= $outputType;
2783 if ( $clearState ) {
2784 $this->clearState();
2789 * Transform a MediaWiki message by replacing magic variables.
2791 * @param string $text the text to transform
2792 * @param ParserOptions $options options
2793 * @return string the text with variables substituted
2796 function transformMsg( $text, $options ) {
2798 static $executing = false;
2800 # Guard against infinite recursion
2806 $this->mTitle
= $wgTitle;
2807 $this->mOptions
= $options;
2808 $this->mOutputType
= OT_MSG
;
2809 $this->clearState();
2810 $text = $this->replaceVariables( $text );
2817 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2818 * Callback will be called with the text within
2819 * Transform and return the text within
2822 function setHook( $tag, $callback ) {
2823 $oldVal = @$this->mTagHooks
[$tag];
2824 $this->mTagHooks
[$tag] = $callback;
2829 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2830 * Placeholders created in Skin::makeLinkObj()
2831 * Returns an array of links found, indexed by PDBK:
2835 * $options is a bit field, RLH_FOR_UPDATE to select for update
2837 function replaceLinkHolders( &$text, $options = 0 ) {
2838 global $wgUser, $wgLinkCache;
2839 global $wgOutputReplace;
2841 $fname = 'Parser::replaceLinkHolders';
2842 wfProfileIn( $fname );
2846 $sk = $this->mOptions
->getSkin();
2848 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
2849 wfProfileIn( $fname.'-check' );
2850 $dbr =& wfGetDB( DB_SLAVE
);
2851 $page = $dbr->tableName( 'page' );
2852 $threshold = $wgUser->getOption('stubthreshold');
2855 asort( $this->mLinkHolders
['namespaces'] );
2859 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
2861 $title = $this->mLinkHolders
['titles'][$key];
2863 # Skip invalid entries.
2864 # Result will be ugly, but prevents crash.
2865 if ( is_null( $title ) ) {
2868 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2870 # Check if it's in the link cache already
2871 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2872 $colours[$pdbk] = 1;
2873 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2874 $colours[$pdbk] = 0;
2876 # Not in the link cache, add it to the query
2877 if ( !isset( $current ) ) {
2879 $query = "SELECT page_id, page_namespace, page_title";
2880 if ( $threshold > 0 ) {
2881 $query .= ', page_len, page_is_redirect';
2883 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2884 } elseif ( $current != $val ) {
2886 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2891 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
2896 if ( $options & RLH_FOR_UPDATE
) {
2897 $query .= ' FOR UPDATE';
2900 $res = $dbr->query( $query, $fname );
2902 # Fetch data and form into an associative array
2903 # non-existent = broken
2906 while ( $s = $dbr->fetchObject($res) ) {
2907 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
2908 $pdbk = $title->getPrefixedDBkey();
2909 $wgLinkCache->addGoodLink( $s->page_id
, $pdbk );
2911 if ( $threshold > 0 ) {
2912 $size = $s->page_len
;
2913 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
2914 $colours[$pdbk] = 1;
2916 $colours[$pdbk] = 2;
2919 $colours[$pdbk] = 1;
2923 wfProfileOut( $fname.'-check' );
2925 # Construct search and replace arrays
2926 wfProfileIn( $fname.'-construct' );
2927 $wgOutputReplace = array();
2928 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
2929 $pdbk = $pdbks[$key];
2930 $searchkey = "<!--LINK $key-->";
2931 $title = $this->mLinkHolders
['titles'][$key];
2932 if ( empty( $colours[$pdbk] ) ) {
2933 $wgLinkCache->addBadLink( $pdbk );
2934 $colours[$pdbk] = 0;
2935 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2936 $this->mLinkHolders
['texts'][$key],
2937 $this->mLinkHolders
['queries'][$key] );
2938 } elseif ( $colours[$pdbk] == 1 ) {
2939 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2940 $this->mLinkHolders
['texts'][$key],
2941 $this->mLinkHolders
['queries'][$key] );
2942 } elseif ( $colours[$pdbk] == 2 ) {
2943 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2944 $this->mLinkHolders
['texts'][$key],
2945 $this->mLinkHolders
['queries'][$key] );
2948 wfProfileOut( $fname.'-construct' );
2951 wfProfileIn( $fname.'-replace' );
2953 $text = preg_replace_callback(
2954 '/(<!--LINK .*?-->)/',
2955 "wfOutputReplaceMatches",
2958 wfProfileOut( $fname.'-replace' );
2961 # Now process interwiki link holders
2962 # This is quite a bit simpler than internal links
2963 if ( !empty( $this->mInterwikiLinkHolders
) ) {
2964 wfProfileIn( $fname.'-interwiki' );
2965 # Make interwiki link HTML
2966 $wgOutputReplace = array();
2967 foreach( $this->mInterwikiLinkHolders
as $i => $lh ) {
2968 $s = $sk->makeLink( $lh[0], $lh[1] );
2969 $wgOutputReplace[] = $s;
2972 $text = preg_replace_callback(
2973 '/<!--IWLINK (.*?)-->/',
2974 "wfOutputReplaceMatches",
2976 wfProfileOut( $fname.'-interwiki' );
2979 wfProfileOut( $fname );
2984 * Renders an image gallery from a text with one line per image.
2985 * text labels may be given by using |-style alternative text. E.g.
2986 * Image:one.jpg|The number "1"
2987 * Image:tree.jpg|A tree
2988 * given as text will return the HTML of a gallery with two images,
2989 * labeled 'The number "1"' and
2994 function renderImageGallery( $text ) {
2996 global $wgUser, $wgParser, $wgTitle;
2997 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2999 global $wgLinkCache;
3000 $ig = new ImageGallery();
3001 $ig->setShowBytes( false );
3002 $ig->setShowFilename( false );
3003 $lines = explode( "\n", $text );
3005 foreach ( $lines as $line ) {
3006 # match lines like these:
3007 # Image:someimage.jpg|This is some image
3008 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3010 if ( count( $matches ) == 0 ) {
3013 $nt = Title
::newFromURL( $matches[1] );
3014 if( is_null( $nt ) ) {
3015 # Bogus title. Ignore these so we don't bomb out later.
3018 if ( isset( $matches[3] ) ) {
3019 $label = $matches[3];
3024 $html = $wgParser->parse( $label , $wgTitle, $parserOptions );
3025 $html = $html->mText
;
3027 $ig->add( new Image( $nt ), $html );
3028 $wgLinkCache->addImageLinkObj( $nt );
3030 return $ig->toHTML();
3034 * Parse image options text and use it to make an image
3036 function makeImage( &$nt, $options ) {
3037 global $wgContLang, $wgUseImageResize;
3038 global $wgUser, $wgThumbLimits;
3042 # Check if the options text is of the form "options|alt text"
3044 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3045 # * left no resizing, just left align. label is used for alt= only
3046 # * right same, but right aligned
3047 # * none same, but not aligned
3048 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3049 # * center center the image
3050 # * framed Keep original image size, no magnify-button.
3052 $part = explode( '|', $options);
3054 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3055 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3056 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3057 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3058 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3059 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3060 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3063 $width = $height = $framed = $thumb = false;
3064 $manual_thumb = "" ;
3066 foreach( $part as $key => $val ) {
3067 $val_parts = explode ( "=" , $val , 2 ) ;
3068 $left_part = array_shift ( $val_parts ) ;
3069 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3071 } elseif ( $wgUseImageResize && count ( $val_parts ) == 1 && ! is_null( $mwThumb->matchVariableStartToEnd($left_part) ) ) {
3072 # use manually specified thumbnail
3074 $manual_thumb = array_shift ( $val_parts ) ;
3075 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3076 # remember to set an alignment, don't render immediately
3078 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3079 # remember to set an alignment, don't render immediately
3081 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3082 # remember to set an alignment, don't render immediately
3084 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3085 # remember to set an alignment, don't render immediately
3087 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3088 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3089 # $match is the image width in pixels
3090 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3091 $width = intval( $m[1] );
3092 $height = intval( $m[2] );
3094 $width = intval($match);
3096 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3102 # Strip bad stuff out of the alt text
3104 $this->replaceLinkHolders( $alt );
3105 $alt = Sanitizer
::stripAllTags( $alt );
3107 # Linker does the rest
3108 $sk =& $this->mOptions
->getSkin();
3109 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3115 * @package MediaWiki
3119 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3120 var $mCacheTime; # Used in ParserCache
3121 var $mVersion; # Compatibility check
3122 var $mTitleText; # title text of the chosen language variant
3123 var $mLcfirstTitle; # This is true if the first letter in the title has to be lowercase
3125 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3126 $containsOldMagic = false, $titletext = '' )
3128 $this->mText
= $text;
3129 $this->mLanguageLinks
= $languageLinks;
3130 $this->mCategoryLinks
= $categoryLinks;
3131 $this->mContainsOldMagic
= $containsOldMagic;
3132 $this->mCacheTime
= '';
3133 $this->mVersion
= MW_PARSER_VERSION
;
3134 $this->mTitleText
= $titletext;
3137 function getText() { return $this->mText
; }
3138 function getLanguageLinks() { return $this->mLanguageLinks
; }
3139 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3140 function getCacheTime() { return $this->mCacheTime
; }
3141 function getTitleText() { return $this->mTitleText
; }
3142 function getLcfirstTitle() { return $this->mLcfirstTitle
; }
3143 function containsOldMagic() { return $this->mContainsOldMagic
; }
3144 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3145 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3146 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3147 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3148 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3149 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3151 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3153 function merge( $other ) {
3154 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3155 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3156 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3160 * Return true if this cached output object predates the global or
3161 * per-article cache invalidation timestamps, or if it comes from
3162 * an incompatible older version.
3164 * @param string $touched the affected article's last touched timestamp
3168 function expired( $touched ) {
3169 global $wgCacheEpoch;
3170 return $this->getCacheTime() <= $touched ||
3171 $this->getCacheTime() <= $wgCacheEpoch ||
3172 !isset( $this->mVersion
) ||
3173 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3178 * Set options of the Parser
3180 * @package MediaWiki
3184 # All variables are private
3185 var $mUseTeX; # Use texvc to expand <math> tags
3186 var $mUseDynamicDates; # Use DateFormatter to format dates
3187 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3188 var $mAllowExternalImages; # Allow external images inline
3189 var $mSkin; # Reference to the preferred skin
3190 var $mDateFormat; # Date format index
3191 var $mEditSection; # Create "edit section" links
3192 var $mNumberHeadings; # Automatically number headings
3194 function getUseTeX() { return $this->mUseTeX
; }
3195 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3196 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3197 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3198 function getSkin() { return $this->mSkin
; }
3199 function getDateFormat() { return $this->mDateFormat
; }
3200 function getEditSection() { return $this->mEditSection
; }
3201 function getNumberHeadings() { return $this->mNumberHeadings
; }
3203 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3204 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3205 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3206 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3207 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3208 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3209 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3211 function setSkin( &$x ) { $this->mSkin
=& $x; }
3214 * Get parser options
3217 function newFromUser( &$user ) {
3218 $popts = new ParserOptions
;
3219 $popts->initialiseFromUser( $user );
3223 /** Get user options */
3224 function initialiseFromUser( &$userInput ) {
3225 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3226 $fname = 'ParserOptions::initialiseFromUser';
3227 wfProfileIn( $fname );
3228 if ( !$userInput ) {
3230 $user->setLoaded( true );
3232 $user =& $userInput;
3235 $this->mUseTeX
= $wgUseTeX;
3236 $this->mUseDynamicDates
= $wgUseDynamicDates;
3237 $this->mInterwikiMagic
= $wgInterwikiMagic;
3238 $this->mAllowExternalImages
= $wgAllowExternalImages;
3239 wfProfileIn( $fname.'-skin' );
3240 $this->mSkin
=& $user->getSkin();
3241 wfProfileOut( $fname.'-skin' );
3242 $this->mDateFormat
= $user->getOption( 'date' );
3243 $this->mEditSection
= $user->getOption( 'editsection' );
3244 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3245 wfProfileOut( $fname );
3250 * Callback function used by Parser::replaceLinkHolders()
3251 * to substitute link placeholders.
3253 function &wfOutputReplaceMatches( $matches ) {
3254 global $wgOutputReplace;
3255 return $wgOutputReplace[$matches[1]];
3259 * Return the total number of articles
3261 function wfNumberOfArticles() {
3262 global $wgNumberOfArticles;
3265 return $wgNumberOfArticles;
3269 * Get various statistics from the database
3272 function wfLoadSiteStats() {
3273 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3274 $fname = 'wfLoadSiteStats';
3276 if ( -1 != $wgNumberOfArticles ) return;
3277 $dbr =& wfGetDB( DB_SLAVE
);
3278 $s = $dbr->selectRow( 'site_stats',
3279 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3280 array( 'ss_row_id' => 1 ), $fname
3283 if ( $s === false ) {
3286 $wgTotalViews = $s->ss_total_views
;
3287 $wgTotalEdits = $s->ss_total_edits
;
3288 $wgNumberOfArticles = $s->ss_good_articles
;
3294 * Basicly replacing " > and < with HTML entities ( ", >, <)
3296 * @param string $in Text that might contain HTML tags
3297 * @return string Escaped string
3299 function wfEscapeHTMLTagsOnly( $in ) {
3301 array( '"', '>', '<' ),
3302 array( '"', '>', '<' ),